package
{
	import flash.events.MouseEvent;
	import com.happyelements.components.MapScene;
	import com.happyelements.data.DataModel;

	/**
	 * @author dongpiggyi
	 */
	public class MapSceneContext
	{
		private var _addingTileState:IMapSceneState;

		private var _draggingMapState:IMapSceneState;

		private var _currentState:IMapSceneState;
		
		private var _beforeDraggingState:IMapSceneState;
		
		private var _mapScene:MapScene;
		
		private var _addingDataModel:DataModel;
		
		public var currentX:Number;
		
		public var currentY:Number;

		public function MapSceneContext()
		{
			_addingTileState = new AddingTileState(this);
			
			_draggingMapState = new DraggingMapState(this);
			
			_currentState = _draggingMapState;
		}

		public function setup(mapScene:MapScene):void
		{
			_mapScene = mapScene;
			mapScene.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
		}

		private function onDown(event:MouseEvent):void
		{
			currentState.onMouseDown(_mapScene, event.stageX, event.stageY);
			_mapScene.addEventListener(MouseEvent.MOUSE_MOVE, onMove);
			_mapScene.addEventListener(MouseEvent.MOUSE_UP, onUp);
		}

		private function onUp(event:MouseEvent):void
		{
			currentState.onMouseUp(_mapScene, event.stageX, event.stageY);
			_mapScene.removeEventListener(MouseEvent.MOUSE_MOVE, onMove);
			_mapScene.removeEventListener(MouseEvent.MOUSE_UP, onUp);
		}

		private function onMove(event:MouseEvent):void
		{
			currentState.onMouseMove(_mapScene, event.stageX, event.stageY);
		}

		private function onAddingTile(event:MouseEvent):void
		{
			currentState.onAddingTile(_mapScene, event.stageX, event.stageY, _addingDataModel);
		}
		
		public function get currentState():IMapSceneState
		{
			return _currentState;
		}

		public function set currentState(currentState:IMapSceneState):void
		{
			this._currentState = currentState;
			
			if (currentState == addingTileState)
			{
				_mapScene.addEventListener(MouseEvent.MOUSE_MOVE, onAddingTile);
			}
			else if(_mapScene.hasEventListener(MouseEvent.MOUSE_MOVE))
			{
				_mapScene.removeEventListener(MouseEvent.MOUSE_MOVE, onAddingTile);
			}
		}

		public function get addingTileState():IMapSceneState
		{
			return _addingTileState;
		}

		public function get draggingMapState():IMapSceneState
		{
			return _draggingMapState;
		}
		
		public function get beforeDraggingState():IMapSceneState
		{
			return _beforeDraggingState;
		}

		public function set beforeDraggingState(beforeDraggingState:IMapSceneState):void
		{
			_beforeDraggingState = beforeDraggingState;
		}
		
		public function get addingDataModel():DataModel
		{
			return _addingDataModel;
		}

		public function set addingDataModel(addingDataModel:DataModel):void
		{
			trace("adding data model, different from before: " + (_addingDataModel != addingDataModel));
			_addingDataModel = addingDataModel;
		}
	}
}

